/**
 * 129. 求根节点到叶节点数字之和
 * https://leetcode.cn/problems/sum-root-to-leaf-numbers/description/
 */

class Solution2 {
    public int sumNumbers(TreeNode root) {
        int ret = dfs(root, 0);
        return ret;
    }

    public int dfs(TreeNode root, int preSum) {
        preSum = preSum * 10 + root.val;
        
        if(root.left == null && root.right == null) return preSum;

        int ret = 0;
        if(root.left != null) ret += dfs(root.left, preSum);
        if(root.right != null) ret += dfs(root.right, preSum);

        return ret;
    }
}